package com.flute.haflute.monitor;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flute.haflute.common.ClusterConstants;
import com.flute.haflute.net.RMILocalClient;
import com.flute.haflute.net.RMINetClient;

/**
 * 消息发送者
 * 
 */
public class MessageTransfer {
	private static Logger logger = LoggerFactory
			.getLogger(MessageTransfer.class);

	static Object clusterStatusMessage;
	static Object localStatusMessage;
	static int errorCout = 0;

	/**
	 * 集群消息 用于向DM的通讯
	 * 
	 * @param map
	 */
	public static synchronized void clusterMsgSend(String methodName,
			Map<String, StatusMessage> map) {
		String refId = ClusterConstants.CLUSTER_MONITOR_REF;
		try {
			if (clusterStatusMessage == null) {
				clusterStatusMessage = RMINetClient.getServiceObject(refId);
				logger.info("RMINetClient getServiceObject success ");
				errorCout = 0;
			}
			RMINetClient.invoke(clusterStatusMessage, methodName, map);
		} catch (Exception e) {
			if (errorCout == 0) {
				logger.error("clusterMsgSend error " + e);
				clusterStatusMessage = null;
			}
			errorCout++;
		}

	}

	/**
	 * 本地消息 用于子节点内部通讯
	 * 
	 * @param map
	 */
	public static void localMsgSend(String methodName,
			Map<String, StatusMessage> map) {
		String refId = ClusterConstants.LOCAL_MONITOR_REF;
		try {
			if (localStatusMessage == null) {
				localStatusMessage = RMILocalClient.getServiceObject(refId);
				logger.info("RMILocalClient getServiceObject success ");
				errorCout = 0;
			}
			RMILocalClient.invoke(localStatusMessage, methodName, map);
		} catch (Exception e) {
			if (errorCout == 0) {
				logger.error("sendMsg error " + e);
				localStatusMessage = null;
			}
			errorCout++;
		}

	}

}
